/**
 * Copyright SunEEE Limited (c) 2014. All rights reserved.
 * This software is proprietary to and embodies the confidential
 * technology of SunEEE Limited.  Possession, use, or copying
 * of this software and media is authorized only pursuant to a
 * valid written license from SunEEE or an authorized sublicensor.
 */
package com.suneee.base.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
/**
 * ZhiLi:      MD5加密
 * @version   Revision History
 * <pre>
 * Author     Version       Date              Changes
 * ZhiLi      1.0           2014年11月6日     Created
 *
 * </pre>
 * @since B2B1.0.0
 */

public abstract class MD5Utils {

    private static final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//    private static final char[] HEXDIGITS = { '0', 'A', '1', 'B', '2', 'C', '3', 'D', '4', '5', '6', 'E', '7', '8',
//            '9', 'F' };

    /**
     * 静态化消息摘要。
     */
    private static final MessageDigest md;

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw ErrorUtils.wrap(e);
        }
    }

    /**
     * MD5加密
     * @param s
     * @return
     */
    public static String md5(String source) {
    	Assert.notEmpty(source, "source");
               
        byte[] digest = MD5Utils.digest(source.getBytes());

        //把密文转换成十六进制的字符串形式
        int j = digest.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte b = digest[i];
            str[k++] = HEXDIGITS[b >>> 4 & 0xf];
            str[k++] = HEXDIGITS[b & 0xf];
        }
        return new String(str);
    }

    /**
     * 获取加密字节数组
     * @param bs
     * @return
     */
    private static synchronized byte[] digest(byte[] bs) {
        //获得MD5摘要算法的 MessageDigest 对象  
        //获得密文  
        return md.digest(bs);
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.md5("中国广东省广州市天河区东圃镇朱村64栋2单元50318665061881"));
        //539D51A453C9ED17516C2588C6BB0AA1
        //9A0687B525E6C56EE9C390CDF10F44B9
    }

}
